import type { ErrorLogInfo } from "#/store";
import { defineStore } from "pinia";
import { computed, ref, type Ref } from "vue";
import { formatToDateTime } from "@/utils/date-util";
import { ErrorTypeEnum } from "@/models/enums/exception";
import { store } from ".";

export const useErrorLogStore = defineStore("app-error-log", () => {
  const errorLogs: Ref<ErrorLogInfo[]> = ref([]);
  const errorLogCount = computed(() => errorLogs.value.length);

  const getErrorLogs = () => {
    return errorLogs;
  };
  const getErrorLogCount = () => {
    return errorLogCount;
  };

  const addErrorLogInfo = (info: ErrorLogInfo) => {
    const item = {
      ...info,
      time: formatToDateTime(new Date()),
    };
    errorLogs.value.push(item);
  };

  const addAjaxErrorInfo = (error: any) => {
    const errInfo: Partial<ErrorLogInfo> = {
      message: error.message,
      type: ErrorTypeEnum.AJAX,
    };
    if (error.response) {
      const { config: { url = "", data: params = "", method = "get", headers = {} } = {}, data = {} } = error.response;
      errInfo.url = url;
      errInfo.name = "Ajax Error!";
      errInfo.file = "-";
      errInfo.stack = JSON.stringify(data);
      errInfo.detail = JSON.stringify({ params, method, headers });
    }
    addErrorLogInfo(errInfo as ErrorLogInfo);
  };
  return { getErrorLogs, getErrorLogCount, addErrorLogInfo, addAjaxErrorInfo };
});

/**
 * @description 错误日志 (在setup方法外使用此方法)
 */
export function useErrorLogStoreWithOut() {
  return useErrorLogStore(store);
}
